
layui.use(['form', 'layer', 'laydate', 'table', 'upload'], function(){

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        upload = layui.upload,
        table = layui.table;

    var datalist_url = $('.datalist_url').val();
    var add_url = $('.add_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var edit_receiving_car_url = $('.edit_receiving_car').val();
    var save_receiving_url = $('.save_receiving').val();



    // Table 列表
    var tableIns = table.render({
        elem: '#dataTable',
        url : datalist_url,
        page : false,
        where: {
            purchase_id:$('#purchase_id').val()
        },
        cellMinWidth : 95,
        //height : "full-100",
        limit : 10,
        limits : [10, 20, 50, 100],
        id : "tableList",
        // initSort: {
        //     field: 'product_name' // 排序字段，对应 cols 设定的各字段名
        //     ,type: 'asc' // 排序方式  asc: 升序、desc: 降序、null: 默认排序
        // },
        cols : [[
            {type: "checkbox", fixed:"left", width:50,LAY_CHECKED:true},
            {field: 'product_name', title: '商品名称', align:"center"},
            {field: 'bar_code', title: '条码',align:'center'},
            {field: 'spec', title: '规格', align:'center', sort: true},
            {field: 'unit', title: '单位', align:'center'},
            {field: 'purchase_price', title: '进货价', align:'center',templet:function(d){
                return formatMoney(d.purchase_price/100,1)
            }},
            {field: 'pu_stock', title: '采购数量',width:120, align:'center'},
            {field: 'actual_num', title: '收货数量（可编辑）', align:'center',edit:true},
            {field: 'shou_price', title: '收货金额', align:'center',templet:function(d){
                return formatMoney(d.shou_price/100,1)
            }},
            {field: 'production_time', title: '生产日期', align: 'center', width: 200,
                templet: function (d) {
                    return '<input type="text" name="production_time" verify lay-verify="verify" value="' + (d.production_time || '') + '" placeholder="请选择时间" readonly="readonly" class="layui-input layui-input-date" style="text-align: center"/>';
                }},

            {title: '操作', fixed:"right", align:"center", minWidth:140, templet:function(data){
                var html = '';
                html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="add_rece"><i class="layui-icon"></i>添加</a>';
                html += '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon"></i>删除</a>';

                return html;
            }}
        ]],
        done: function (res, curr, count) {
            merge(res);
            //日期控件
            $(".layui-input-date").each(function (i) {
                layui.laydate.render({
                    elem: this,
                    format: "yyyy-MM-dd",
                    done: function (value, date) {
                        if (res && res.data[i]) {
                            $.extend(res.data[i], {'production_time': value})
                        }
                        console.log(res.data[i]);
                        $.ajax({
                            url: '/admin/Receiving/edit_receiving_date',
                            data: {"id": res.data[i].id,"value":value,'purchase_id':res.data[i].purchase_id,'product_id':res.data[i].product_id},
                            type: "POST",
                            dataType: "json",
                            success: function (res) {
                                if (res.code == 1) {
                                    //layer.msg(data.product_name+ ' 的收货数量修改为 ' + value, {icon: 1});
                                    tableIns.reload();
                                } else {
                                    layer.msg(res.msg);
                                    tableIns.reload();
                                }
                            },
                            error: function (data) {
                                layer.msg("服务器无响应");
                            }
                        });

                    }
                });
            });
            console.log(res);
        },
    });

    // Table 列表
    var tableIndex= table.render({
        elem: '#dataTable01',
        url : datalist_url,
        page : true,
        cellMinWidth : 95,
        //height : "full-100",
        limit : 10,
        limits : [10, 20, 50, 100],
        id : "table01List",
        // initSort: {
        //     field: 'product_name' // 排序字段，对应 cols 设定的各字段名
        //     ,type: 'asc' // 排序方式  asc: 升序、desc: 降序、null: 默认排序
        // },
        cols : [[
            {type: "checkbox", fixed:"left", width:50,LAY_CHECKED:true},
            {field: 'id', title: '收货单号', align:"center"},
            {field: 'name', title: '供货商',align:'center'},
            {field: 'purchase_id', title: '采购单号', align:'center', sort: true},
            {field: 'receiving_num', title: '到货数量', align:'center'},
            {field: 'total_price', title: '到货金额', align:'center',templet:function(d){
                return formatMoney(d.total_price/100,1)
            }},
            {field: 'create_date', title: '创建时间',width:180, align:'center'},
            {field: 'login_name', title: '创建人', align:'center'},
            {field: 'remarks', title: '备注', align:'center'},

            {title: '操作', fixed:"right", align:"center", minWidth:140, templet:function(data){
                var html = '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="detail" href="/admin/receiving/detail/id/'+ data.id+'"><i class="layui-icon"></i>详情</a>';
                return html;
            }}
        ]]
    });
    // 搜索
    $(".search_btn").on("click", function(){
        if($('.id').val() != ''){
            table.reload("table01List", {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    id: $('.searchBox').find('.id').val()  //搜索的关键字
                }
            });
        }else{
            layer.msg("请输入搜索的内容");
        }
    });
    // 清空搜索
    $(".reset_btn").on("click", function(){
        table.reload("table01List", {
            where: {
                id: '',
            }
        });
    });

    table.on('edit(dataTable_filter)',function (e) {
        //编辑表格单元格
        if(!checkRate(e.value)){
            tableIns.reload();
            layer.msg('收货数量必须大于0')
        }else {
            var value = e.value //得到修改后的值
                ,data = e.data //得到所在行所有键值
            if(value <= data.pu_stock){
                $.ajax({
                    url: edit_receiving_car_url,
                    data: {"id": data.id,"value":value,'purchase_id':data.purchase_id,'product_id':data.product_id},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg(data.product_name+ ' 的收货数量修改为 ' + value, {icon: 1});
                            tableIns.reload();
                        } else {
                            layer.msg(res.msg);
                            tableIns.reload();
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            }else {
                layer.msg("收货数量应该小于等于采购数量");
                tableIns.reload();
            }
        }
    })

    // 批量删除
    $(".delAll_btn").on("click", function(){
        var checkStatus = table.checkStatus('tableList'),
            data = checkStatus.data,
            ids = [];
        if(data.length > 0) {
            for (var i in data) {
                ids.push(data[i].id);
            }
            layer.confirm('确定删除选中的数据？', {icon: 3, title: '提示信息'}, function (index) {
                $.ajax({
                    url: delete_url,
                    data: {"ids": ids},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('删除成功', {icon: 1});
                            tableIns.reload();
                            layer.close(index);
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            })
        }else{
            layer.msg("请选择需要删除的数据");
        }
    });


    $('.add_btn').on('click', function(){
        layer.open({
            type: 1
            , anim: 1
            , title: '选择供应商'
            ,btn: ['确定']
            , closeBtn: 1
            , shade: 0.2
            , shadeClose: true // 是否点击遮罩关闭
            , skin: 'layui-anim layui-anim-rl layui-layer-Elasticframe'
            , area: ['600px','400px']
            , content: $('#supspr')
            ,yes: function(index, layero){
                var purchase_id = $('#receivselect').val();
                var supid = $('#supsprselect').val();
                if(supid ==0 || purchase_id == 0){
                    layer.msg('请选择供货商或者采购订单');
                }else {
                    layer.close(index);
                    window.location.href = '/admin/receiving/add/purchase_id/' + purchase_id + '/supid/' + supid
                }
                //按钮【按钮一】的回调
            }
        });
        $(".layui-layer-shade").css("display","none");
        //其中：layero是弹层的DOM对象
        // $('#view-modal').modal('toggle');
    });

    form.on('select(supsprselect)', function(data){
        var supid=data.value;
        $.ajax({
            type: 'POST',
            url: '/admin/Receiving/getpurchase',
            data: {supid:supid},
            dataType:  'json',
            success: function(data){
                $("#receivselect").html("");
                $.each(data, function(key, val) {
                    var option1 = $("<option>").val(val.id).text('单据号  '+val.id);
                    $("#receivselect").append(option1);
                    form.render('select');
                });
                $("#receivselect").get(0).selectedIndex=0;
            }
        });
    });

    $('.save_btn').on('click',function () {
        var checkStatus = table.checkStatus('tableList');
        var data = checkStatus.data;
        var temp = [];
        if(data.length > 0){
            var map = {},
                dest = [];
            for (var i = 0;i<data.length;i++) {
                if(data[i].shou_price == 0){
                    layer.msg("收货金额必须大于0");
                    return false;
                }
                if(data[i].production_time == null){
                    layer.msg("商品的生产日期必填");
                    return false;
                }

                var ai = data[i];
                if(!map[ai.product_id]){
                    dest.push({
                        product_id: ai.product_id,
                        product_name: ai.product_name,
                        pu_stock:ai.pu_stock,
                        data: [ai]
                    });
                    map[ai.product_id] = ai;
                }else{
                    for(var j = 0; j < dest.length; j++){
                        var dj = dest[j];
                        if(dj.product_id == ai.product_id){
                            dj.data.push(ai);
                            break;
                        }
                    }
                }

                var datas = {
                    purchase_price:data[i].purchase_price,
                    bar_code:data[i].bar_code,
                    actual_num:data[i].actual_num,
                    purchase_id:data[i].purchase_id,
                    product_id:data[i].product_id,
                    production_time:data[i].production_time,
                };
                temp.push(datas)
            }
            var data = JSON.stringify(temp)
            var content = "";
            for(var i=0;i<dest.length;i++){
                var all_shou = 0;
                for(var j=0;j<dest[i].data.length;j++){
                    all_shou += dest[i].data[j].actual_num
                }
                dest[i].all_shou = all_shou;
                content += "商品" + dest[i].product_name+ "：" + "采购数量为" + dest[i].pu_stock + "，实际收货数量为" + dest[i].all_shou + '<br/>'
            }
            var remarks =  '';
            if($('#remarks').val().trim() != ''){
                remarks = $('#remarks').val();
            }
            layer.alert(content, {
                skin: 'layui-layer-molv' //样式类名  自定义样式
                ,closeBtn: 1    // 是否显示关闭按钮
                ,anim: 1 //动画类型
                ,title:'确认收货吗？'
                ,area: ['420px', '240px'] //宽高
                ,btn: ['确定'] //按钮
                ,icon: 7    // icon
                ,yes:function(){
                    $.ajax({
                        url: save_receiving_url,
                        data: {data,"remarks":remarks,dest},
                        type: "POST",
                        dataType: "json",
                        success: function (res) {
                            if (res.code == 1) {
                                layer.msg(res.msg);
                                window.location.href = res.url
                            } else {
                                layer.msg(res.msg);
                            }
                        },
                        error: function (data) {
                            layer.msg("服务器无响应");
                        }
                    });
                }
                });

        }else {
            layer.msg("请搜索并选择商品");
        }
    });


    // 列表操作
    table.on('tool(dataTable_filter)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
            console.log(data);
        // 删除
        if (layEvent === 'del') {
            layer.confirm('确定删除此数据？',{icon:3, title:'提示信息'},function(index){
                $.ajax({
                    url: delete_url,
                    data: {"id": data.id},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('已删除', {icon: 1, time: 1000});
                            tableIns.reload();
                            layer.close(index);
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            });
        } else if(layEvent === 'add_rece'){
            console.log(data)
            if(data.pu_stock < 2){
                layer.msg("此商品只采购了一件");
                return false;
            }
            $.ajax({
                url: '/admin/Receiving/add_rece',
                data: {data},
                type: "POST",
                dataType: "json",
                success: function (res) {
                    if (res.code == 1) {
                        tableIns.reload();
                    } else {
                        layer.msg(res.msg);
                    }
                },
                error: function (data) {
                    layer.msg("服务器无响应");
                }
            });
            //formHtml(data);
        }
    });

    // Form 表单
    function formHtml(data){
        var content = add_url;
        if(data){
            content = edit_url + '?id=' + data.id;
        }
        // 右侧面板
        var index = layer.open({
            type: 2
            , anim: -1
            , title: false
            , closeBtn: false
            , offset: 'r'
            , shade: 0.2
            //, shadeClose: true // 是否点击遮罩关闭
            , skin: 'layui-anim layui-anim-rl layui-layer-adminRight'
            , area: '800px'
            , top: 0
            , content: content
        });
    }

    // 表单提交
    form.on("submit(laySave)", function(data){
        //弹出loading
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});

    })

    //单元格行合并
    function merge(res) {
        var data = res.data;
        var mergeIndex = 0;//定位需要添加合并属性的行数
        var mark = 1; //这里涉及到简单的运算，mark是计算每次需要合并的格子数
        var columsName = ['product_name','bar_code','pu_stock'];//需要合并的列名称
        var columsIndex = [1,2,6];//需要合并的列索引值

        for (var k = 0; k < columsName.length; k++) { //这里循环所有要合并的列
            var trArr = $(".layui-table-body>.layui-table").find("tr");//所有行
            for (var i = 1; i < res.data.length; i++) { //这里循环表格当前的数据
                var tdCurArr = trArr.eq(i).find("td").eq(columsIndex[k]);//获取当前行的当前列
                var tdPreArr = trArr.eq(mergeIndex).find("td").eq(columsIndex[k]);//获取相同列的第一列

                if (data[i][columsName[k]] === data[i-1][columsName[k]] && data[i][columsName[0]] === data[i-1][columsName[0]]) { //后一行的值与前一行的值做比较，相同就需要合并
                    mark += 1;
                    tdPreArr.each(function () {//相同列的第一列增加rowspan属性
                        $(this).attr("rowspan", mark);
                    });
                    tdCurArr.each(function () {//当前行隐藏
                        $(this).css("display", "none");
                    });

                }else {
                    mergeIndex = i;
                    mark = 1;//一旦前后两行的值不一样了，那么需要合并的格子数mark就需要重新计算
                }
            }
            mergeIndex = 0;
            mark = 1;
        }
    }

});